package com.blog4j.server.modules.email.core;

import com.blog4j.common.enums.EmailTypeEnum;
import com.blog4j.common.enums.ErrorEnum;
import com.blog4j.common.exception.Blog4jException;
import com.blog4j.common.utils.ValidateUtil;
import com.blog4j.server.modules.email.context.EmailContext;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;

import java.util.Objects;

/**
 * @author 98k灬
 * @version v1.0.0
 * @Description : 功能描述
 * @Create on : 2024/8/14 12:26
 **/
@Slf4j
public abstract class AbstractEmailEngine implements EmailEngine {
    /**
     * 发送邮件
     *
     * @param emailContext 上下文信息
     */
    @Override
    public void sendEmail(EmailContext emailContext) {
        // 验证
        validation(emailContext);
        // 发送邮件
        if (Objects.equals(emailContext.getEmailTypeEnum(), EmailTypeEnum.NOTICE_EMAIL)) {
            doSendNoticeEmail(emailContext);
            return;
        }
        doSendSystemEmail(emailContext);
    }

    protected abstract void doSendNoticeEmail(EmailContext emailContext);

    protected abstract void doSendSystemEmail(EmailContext emailContext);

    private void validation(EmailContext emailContext) {
        String email = emailContext.getEmail();
        String from = emailContext.getFrom();
        String content = emailContext.getContent();
        String subject = emailContext.getSubject();
        EmailTypeEnum emailType = emailContext.getEmailTypeEnum();
        if (StringUtils.isBlank(email)) {
            throw new Blog4jException(ErrorEnum.EMAIL_EMPTY_ERROR);
        }

        if (StringUtils.isBlank(from) || StringUtils.isBlank(content) || Objects.isNull(emailType) || Objects.isNull(subject)) {
            throw new Blog4jException(ErrorEnum.INVALID_PARAMETER_ERROR);
        }

        if (!ValidateUtil.isValidEmail(email)) {
            throw new Blog4jException(ErrorEnum.EMAIL_ERROR);
        }
    }
}
